var oper = getQueryString('oper')
var id = getQueryString('id')
$(function () {
    $('#oper').val(oper)
    if (oper === 'edit' || oper === 'view') {
        clientDetail(id)
    } else {
        var result = {
            oper: oper,
        }
        renderTpl('formTpl', result, 'formBox')
        tplInit()
        validateForm()
        renderDictCheck('#typeBox', 'grant_types', 'authorizedGrantTypes')
    }

    jQuery.validator.addMethod("format", function (value, element) {
        var account = /^[a-zA-Z0-9_]*$/;
        return account.test(value);
    }, "只支持字母、数字、下划线");

    jQuery.validator.addMethod("isNumber", function (value, element) {
        if (value) {
            var account = /^\d*$/;
            return account.test(value) && value > 0 && value < 9999999;
        }
        return true
    }, "请输入0 ~ 99999 的整数");

    jQuery.validator.addMethod("isJSON", function (value, element) {
        if (value) {
            if (typeof value == 'string') {
                try {
                    var obj = JSON.parse(value);
                    if (typeof obj == 'object' && obj) {
                        return true;
                    } else {
                        return false;
                    }

                } catch (e) {
                    return false;
                }
            }
        }
        return true;
    }, "请输入 JSON 类型的数据");

    jQuery.validator.addMethod("clientIdRepeat", function (value, element) {
        var result;
        $.ajax({
            url: api + '/admin/client/' + value,
            async: false,
            type: 'get',
            success: function (res) {
                result = !Boolean(res.data[0])
            }
        });
        return result
    }, "客户端已存在");
});

function validateForm() {
    $("#editForm").validate({
        onkeyup: false,
        rules: {
            clientId: {
                required: true,
                format: true,
                clientIdRepeat: oper === 'add',
            },
            clientSecret: {
                required: true
            },
            scope: {
                required: true
            },
            autoapprove: {
                required: true
            },
            authorizedGrantTypes: {
                required: true
            },
            accessTokenValidity: {
                isNumber: true,
            },
            refreshTokenValidity: {
                isNumber: true,
            },
            additionalInformation: {
                isJSON: true,
            }
        },
        messages: {
            clientId: {
                required: "请输入clientId"
            },
            clientSecret: {
                required: "请输入clientSecret"
            },
            scope: {
                required: "请输入scope"
            },
            autoapprove: {
                required: "请选择自动放行"
            },
            authorizedGrantTypes: {
                required: "请选择授权模式"
            }
        },
        focusCleanup: true
    });
}


function clientDetail(id) {
    $.operate.get(api + '/admin/client/id/' + id, function (res) {
        res.data.oper = oper
        renderTpl('formTpl', res.data, 'formBox')
        tplInit()
        validateForm()
        renderDictCheck('#typeBox', 'grant_types', 'authorizedGrantTypes')
        var channels = res.data.authorizedGrantTypes;
        $.each($('input[name=authorizedGrantTypes]'), function () {
            var temp = $(this).val().toString()
            if (channels.indexOf(temp) >= 0) {
                $(this).prop("checked", true)
                $(this).parent().addClass("checked")
            }
        })
        initFormInfo();
        
    }, false)
}

function submitHandler() {
    var types = []
    $.each($('input[name=authorizedGrantTypes]:checked'), function () {
        types.push($(this).val())
    })
    var accessTime = $('#accessTokenValidity').val()
    var refreshTime = $('#refreshTokenValidity').val()

    if (!accessTime) {
        accessTime = 60 * 60 * 12
    }

    if (!refreshTime) {
        refreshTime = 60 * 60 * 24 * 30
    }
    var data = {
        authorizedGrantTypes: types,
        accessTokenValidity: accessTime,
        refreshTokenValidity: refreshTime
    }
    if ($.validate.form()) {
        $.common.ajaxCommitForm($('#editForm'), false, data);
        return false;
    }
}

// function renderDictCheck(obj, type, name) {
//     if (oper === 'edit' || oper === 'add') {
//         var dict = dictByType(type)
//         dict.forEach(function (item) {
//             $(obj).append('<label class="check-box">' +
//                 '<input name="' + name + '" type="checkbox" value="' + item.value + '">' + item.label +
//                 '</label>')
//         })
//     } else if (oper === 'view') {
//         var dict = dictByType(type)
//         dict.forEach(function (item) {
//             $(obj).append('<label class="check-box">' +
//                 '<input name="' + name + '" type="checkbox" value="' + item.value + '" disabled>' + item.label +
//                 '</label>')
//         })
//     }

//     tplInit()
// }

function initFormInfo () {
    var oper = $("#oper").val();
    if ('view' == oper)  //查看
    {
      $("#editForm").find("input,textarea,select").attr("disabled", true);
    }
  }